<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\publicuse\PublicUse;
use app\admin\model\SystemConfig;
use app\admin\model\SystemUploadfile;
use app\common\controller\AdminController;
use app\common\service\MenuService;
use EasyAdmin\upload\Uploadfile;
use think\db\Query;
use think\facade\Cache;
use think\facade\Db;
use think\Request;

class Ajax extends AdminController
{

    /**
     * 初始化后台接口地址
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function initAdmin()
    {
//        echo '<pre>';
//        print_r(Cache::get('initAdmin_' . session('admin.id')));
//        exit;
        $cacheData = Cache::get('initAdmin_' . session('admin.id'));
//        echo '<pre>';
//        print_r($cacheData);
//        exit;
        if ((!empty($cacheData))&&(!empty($cacheData['menuInfo']))) {
            return json($cacheData);
        }
//        echo '<pre>';
//        print_r($cacheData);
//        exit;
        $menuService = new MenuService(session('admin.id'));
        $menuInfo =$menuService->getMenuTree();
//        dump($menuInfo);die();
        $data = [
            'logoInfo' => [
                'title' => sysconfig('site', 'logo_title'),
                'image' => sysconfig('site', 'logo_image'),
                'href'  => __url('index/index'),
            ],
            'homeInfo' => $menuService->getHomeInfo(),
//            'menuInfo' => $menuService->getMenuTree(),
            'menuInfo' => $menuInfo,
        ];
//        dump($data);die();
//        echo '<pre>';
//        print_r($data);
//        exit;
        Cache::tag('initAdmin')->set('initAdmin_' . session('admin.id'), $data);
        return json($data);
    }

    /**
     * 清理缓存接口
     */
    public function clearCache()
    {
        Cache::clear();
        $this->success('清理缓存成功');
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            $this->success($upload['msg'], ['url' => strpos($upload['url'],'http')===false?\request()->domain().$upload['url']:$upload['url']]);
        } else {
            $this->error($upload['msg']);
        }
    }

    /**
     * 上传图片至编辑器
     * @return \think\response\Json
     */
    public function uploadEditor()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('upload'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return json([
                'error'    => [
                    'message' => '上传成功',
                    'number'  => 201,
                ],
                'fileName' => '',
                'uploaded' => 1,
                'url'      => $upload['url'],
            ]);
        } else {
            $this->error($upload['msg']);
        }
    }

    /**
     * 获取上传文件列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUploadFiles()
    {
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $this->model = new SystemUploadfile();
        $count = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->count();
        $list = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        $data = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**ajax下拉框使用的接口
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function ajaxselect(Request $request){
        $data = $request->param();
//        dump($data);die;
        $where = $data;
        if(isset($where['table'])){
            unset($where['table']);
        }
        if(isset($where['name'])){
            unset($where['name']);
        }
        if(isset($where['value'])){
            unset($where['value']);
        }
        if(isset($where['relationship_primary_key'])){
            unset($where['relationship_primary_key']);
        }
        if(isset($where['field'])){
            unset($where['field']);
        }
        $arr = PublicUse::getModelAndField($data['table']);
        if(isset($arr['field']['delete_time'])){
            $where['delete_time'] = 0;
        }
        if(isset($where['formtype'])){
            unset($where['formtype']);
        }
        $where['status'] = 1;
//        dump($arr);die;
        if(isset($data['formtype'])&&$data['formtype']=='treecheckbox'){
            $whereOr = [
                ['pid','=',0],
                ['pid','=',''],
            ];
            $datas = Db::name($data['table'])
                ->where($where)
                ->where(function ($sql)use($whereOr){
                    $sql->whereOr($whereOr);
                })
                ->select();
//        dump($data);exit;
            foreach ($datas as $key=>$value){
                $value['children'] = Db::name($data['table'])
                    ->where('pid',$value[$data['relationship_primary_key']])
                    ->select()->toArray();
                $datas[$key] = $value;
            }
//            $data = $datas;
        }else{
            $field = $data['relationship_primary_key'].','.$data['name'];
            if($data['table']=='region'){
                $field = $field.',type';
                $datas = Db::name($data['table'])
                    ->where($data['name'],'like',"%{$data['value']}%")
                    ->where($where)
//                ->where('delete_time',0)
                    ->field($field)
                    ->select()->each(function ($item){
                        switch ($item['type']){
                            case 0:
                                $item['name'] = $item['name'].'(国)';
                                break;
                            case 1:
//                                $item->name = $item->name.'(省)';
                                $item['name'] = $item['name'].'(省)';
                                break;
                            case 2:
//                                $item->name = $item->name.'(省)';
                                $item['name'] = $item['name'].'(市)';
                                break;
                            case 3:
//                                $item->name = $item->name.'(区/县)';
                                $item['name'] = $item['name'].'(区/县)';
                                break;
                        }
                        return $item;
                    })->toArray();
            }else{
                $datas = Db::name($data['table'])
                    ->where($data['name'],'like',"%{$data['value']}%")
                    ->where($where)
//                ->where('delete_time',0)
                    ->field($field)
                    ->select()->toArray();
            }
        }
        return $this->success('获取成功',$datas);
    }
    public function get_welcome(){

        $optionRecords = [
            'title'=>[
                'text'=>"数据统计"
            ],
            'tooltip'=>[
                'trigger'=>"axis"
            ],
            'legend'=>[
                'data'=>[
                    '订单笔数',
                    '交易金额',
                    '充值金额',
                    '优惠券使用',
                    '会员'
                ]
            ],
            'grid'=>[
                'left'=>'3%',
                'right'=>'4%',
                'bottom'=>'3%',
                'containLabel'=>true,
            ],
            'toolbox'=>[
                'feature'=>[
                    'saveAsImage'=>[

                    ]
                ]
            ],
            'xAxis'=>[
                'type'=>'category',
                'boundaryGap'=>false,
                'data'=>['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            ],
            'yAxis'=>[
                'type'=>'value'
            ],
            'series'=>[
                [
                    'name'=>'订单笔数',
                    'type'=>'line',
                    'stack'=>'增量',
                    'data'=>[120, 132, 101, 134, 90, 230, 210]
                ],
                [
                    'name'=>'交易金额',
                    'type'=>'line',
                    'stack'=>'增量',
                    'data'=>[220, 182, 191, 234, 290, 330, 310]
                ],
                [
                    'name'=>'充值金额',
                    'type'=>'line',
                    'stack'=>'增量',
                    'data'=>[150, 232, 201, 154, 190, 330, 410]
                ],
                [
                    'name'=>'优惠券使用',
                    'type'=>'line',
                    'stack'=>'增量',
                    'data'=>[320, 332, 301, 334, 390, 330, 320]
                ],
                [
                    'name'=>'会员',
                    'type'=>'line',
                    'stack'=>'增量',
                    'data'=>[820, 932, 901, 934, 1290, 1330, 1320]
                ],
            ]

        ];
        $res['optionRecords'] = $optionRecords;
        $res['notice'] = [
            [
                'title'=>'修改选项卡样式',
                'info'=>'界面足够简洁清爽。<br>
                                一个接口几行代码而已直接初始化整个框架，无需复杂操作。<br>
                                支持多tab，可以打开多窗口。<br>
                                支持无限级菜单和对font-awesome图标库的完美支持。<br>
                                失效以及报错菜单无法直接打开，并给出弹出层提示完美的线上用户体验。<br>
                                url地址hash定位，可以清楚看到当前tab的地址信息。<br>
                                刷新页面会保留当前的窗口，并且会定位当前窗口对应左侧菜单栏。<br>
                                移动端的友好支持。<br>',
                'date'=>'2019-07-11 23:06'
            ],
            [
                'title'=>'新增系统404模板',
                'info'=>'界面足够简洁清爽。<br>
                                一个接口几行代码而已直接初始化整个框架，无需复杂操作。<br>
                                支持多tab，可以打开多窗口。<br>
                                支持无限级菜单和对font-awesome图标库的完美支持。<br>
                                失效以及报错菜单无法直接打开，并给出弹出层提示完美的线上用户体验。<br>
                                url地址hash定位，可以清楚看到当前tab的地址信息。<br>
                                刷新页面会保留当前的窗口，并且会定位当前窗口对应左侧菜单栏。<br>
                                移动端的友好支持。<br>',
                'date'=>'2019-07-11 23:06'
            ],
            [
                'title'=>'新增treetable插件和菜单管理样式',
                'info'=>'界面足够简洁清爽。<br>
                                一个接口几行代码而已直接初始化整个框架，无需复杂操作。<br>
                                支持多tab，可以打开多窗口。<br>
                                支持无限级菜单和对font-awesome图标库的完美支持。<br>
                                失效以及报错菜单无法直接打开，并给出弹出层提示完美的线上用户体验。<br>
                                url地址hash定位，可以清楚看到当前tab的地址信息。<br>
                                刷新页面会保留当前的窗口，并且会定位当前窗口对应左侧菜单栏。<br>
                                移动端的友好支持。<br>',
                'date'=>'2019-07-11 23:06'
            ],
            [
                'title'=>'修改logo缩放问题',
                'info'=>'界面足够简洁清爽。<br>
                                一个接口几行代码而已直接初始化整个框架，无需复杂操作。<br>
                                支持多tab，可以打开多窗口。<br>
                                支持无限级菜单和对font-awesome图标库的完美支持。<br>
                                失效以及报错菜单无法直接打开，并给出弹出层提示完美的线上用户体验。<br>
                                url地址hash定位，可以清楚看到当前tab的地址信息。<br>
                                刷新页面会保留当前的窗口，并且会定位当前窗口对应左侧菜单栏。<br>
                                移动端的友好支持。<br>',
                'date'=>'2019-07-11 23:06'
            ],
            [
                'title'=>'修复左侧菜单缩放tab无法移动',
                'info'=>'界面足够简洁清爽。<br>
                                一个接口几行代码而已直接初始化整个框架，无需复杂操作。<br>
                                支持多tab，可以打开多窗口。<br>
                                支持无限级菜单和对font-awesome图标库的完美支持。<br>
                                失效以及报错菜单无法直接打开，并给出弹出层提示完美的线上用户体验。<br>
                                url地址hash定位，可以清楚看到当前tab的地址信息。<br>
                                刷新页面会保留当前的窗口，并且会定位当前窗口对应左侧菜单栏。<br>
                                移动端的友好支持。<br>',
                'date'=>'2019-07-11 23:06'
            ],
            [
                'title'=>'修复多模块菜单栏展开有问题',
                'info'=>'界面足够简洁清爽。<br>
                                一个接口几行代码而已直接初始化整个框架，无需复杂操作。<br>
                                支持多tab，可以打开多窗口。<br>
                                支持无限级菜单和对font-awesome图标库的完美支持。<br>
                                失效以及报错菜单无法直接打开，并给出弹出层提示完美的线上用户体验。<br>
                                url地址hash定位，可以清楚看到当前tab的地址信息。<br>
                                刷新页面会保留当前的窗口，并且会定位当前窗口对应左侧菜单栏。<br>
                                移动端的友好支持。<br>',
                'date'=>'2019-07-11 23:06'
            ],
        ];
        $res['datastatistics'] = [
            'user'=>123,
            'commodity'=>1234,
            'browse'=>12345,
            'order'=>123456,
        ];
        return $this->success('获取成功',$res);
    }
}